<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2019/6/28
 * Time: 10:31
 */

namespace app\common\service\weekAttention;

use think\Db;
use think\facade\Config;
use app\common\service\CommonService;
use app\common\service\airquality\AirQualityStationAqiRealtimeDayService;
use app\common\service\lastWeek\LastWeekControlAnalysisService;
use app\api\controller\AirQualityFeatureAnalysis;


class WeekAttentionControlPredictService
{
    /**
     * 获取AQI减排前预报 TODO 减排前  时间确定下？
     * @author yy by 2019/7/1
     * @param array $param
     * @return mixed
     */
    public function getReduceBeforePredict($param = [])
    {
        # 判断周几
        $week = date('w');
        if ($week == 1) {
            $data = Db::query("select aqi, DATE_FORMAT(predict_time, '%Y-%m-%d') as date
                               from air_quality_station_aqi_forecast_day
                               where region_id = ? and station_id = ? and is_integer = 1 and DATE_FORMAT(publish_time, '%Y-%m-%d') = ? and DATE_FORMAT(predict_time, '%Y-%m-%d') between ? and ?",
                [$param['region_id'], $param['station_id'], $param['start_time'], $param['start_time'], $param['end_time']]);
        } else {
            $yesterday    = date('Y-m-d', strtotime("-1 day"));
            $now          = date('Y-m-d', time());
            $before_data  = Db::query("select aqi, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                               from air_quality_station_aqi_forecast_day
                               where region_id = ? and station_id = ? and is_integer = 1 and publish_time = predict_time and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?",
                [$param['region_id'], $param['station_id'], $param['start_time'], $yesterday]);
            $predict_data = Db::query("select aqi, DATE_FORMAT(predict_time, '%Y-%m-%d') as date
                               from air_quality_station_aqi_forecast_day
                               where region_id = ? and station_id = ? and is_integer = 1 and DATE_FORMAT(publish_time, '%Y-%m-%d') = ? and DATE_FORMAT(predict_time, '%Y-%m-%d') between ? and ?",
                [$param['region_id'], $param['station_id'], $now, $now, $param['end_time']]);
            $data         = array_merge($before_data, $predict_data);
        }
        # 空数据处理
        $lastWeekControlAnalysisService = new LastWeekControlAnalysisService();
        $result                         = $lastWeekControlAnalysisService->getAllData($param, $data, 'aqi');
        return $result;
    }

    /**
     * 空气质量比较
     * @author yy by 2019/7/1
     * @param array $param
     * @return array
     */
    public function getAirQualityCompare($param = [])
    {
        $pollutant_name = str_replace('.', '', strtolower($param['pollutant_name']));
        # 预报值
        # 判断周几
        $week = date('w');
        if ($week == 1) {
            $forecastData = Db::query("select $pollutant_name, DATE_FORMAT(predict_time, '%Y-%m-%d') as date
                               from air_quality_station_aqi_forecast_day
                               where region_id = ? and station_id = ? and is_integer = 1 and DATE_FORMAT(publish_time, '%Y-%m-%d') = ? and DATE_FORMAT(predict_time, '%Y-%m-%d') between ? and ?",
                [$param['region_id'], $param['station_id'], $param['start_time'], $param['start_time'], $param['end_time']]);
        } else {
            $yesterday    = date('Y-m-d', strtotime("-1 day"));
            $now          = date('Y-m-d', time());
            $before_data  = Db::query("select $pollutant_name, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                               from air_quality_station_aqi_forecast_day
                               where region_id = ? and station_id = ? and is_integer = 1 and publish_time = predict_time and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?",
                [$param['region_id'], $param['station_id'], $param['start_time'], $yesterday]);
            $predict_data = Db::query("select $pollutant_name, DATE_FORMAT(predict_time, '%Y-%m-%d') as date
                               from air_quality_station_aqi_forecast_day
                               where region_id = ? and station_id = ? and is_integer = 1 and DATE_FORMAT(publish_time, '%Y-%m-%d') = ? and DATE_FORMAT(predict_time, '%Y-%m-%d') between ? and ?",
                [$param['region_id'], $param['station_id'], $now, $now, $param['end_time']]);
            $forecastData = array_merge($before_data, $predict_data);
        }
        #实测值
        $realData = Db::query("select $pollutant_name, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                                    from air_quality_station_aqi_realtime_day
                                    where region_id = ? and station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?",
            [$param['region_id'], $param['station_id'], $param['start_time'], $param['end_time']]);

        # 历史同期
        $commonService      = new CommonService();
        $history_start_time = $commonService->getHistoryTime($param['start_time']);
        $history_end_time   = $commonService->getHistoryTime($param['end_time']);
        $historyData        = Db::query("select $pollutant_name, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                        from air_quality_station_aqi_realtime_day
                        where region_id = ? and station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?",
            [$param['region_id'], $param['station_id'], $history_start_time, $history_end_time]);

        # 日期补全处理
        $lastWeekControlAnalysisService = new LastWeekControlAnalysisService();
        $forecast_data                  = $lastWeekControlAnalysisService->getAllData($param, $forecastData, $pollutant_name);
        $history_data                   = $lastWeekControlAnalysisService->getAllData(['start_time' => $history_start_time, 'end_time' => $history_end_time], $historyData, $pollutant_name);
        $real_data                      = $lastWeekControlAnalysisService->getAllData($param, $realData, $pollutant_name);
        # 比较闰年多出来的天  以平年的天数的为准
        if (count($forecast_data['date']) < count($history_data['date'])) {
            $cha = array_diff($history_data['date'], $forecast_data['date']);//出现在第一个数组中但其他输入数组中没有的值
            foreach ($history_data['date'] as $k => $v) {
                if ($v == $cha[0]) {
                    unset($history_data['data'][0][$k]);
                }
            }
        } elseif (count($history_data['date']) < count($forecast_data['date'])) {
            $cha = array_diff($forecast_data['date'], $history_data['date']);//出现在第一个数组中但其他输入数组中没有的值
            foreach ($forecast_data['date'] as $k => $v) {
                if ($v == $cha[0]) {
                    unset($forecast_data['data'][0][$k]);
                    unset($real_data['data'][0][$k]);
                }
            }
        }
        $result = [
            'date' => $forecast_data['date'],
            'data' => [$history_data['data'][0], $forecast_data['data'][0], $real_data['data'][0]]
        ];
        return $result;
    }

    /**
     * 获取非工业贡献度明细（分地区）
     * @author yy by 2019/6/29
     * @param array $param
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getContributionDetail($param = [])
    {
        $commonService = new CommonService();
        # 查询所有的非工业溯源地区
        $non_region        = Db::query("select id,name from basic_non_industry_area where delete_time = 0");
        $non_region_id_arr = array_column($non_region, 'id');
        $lookTime          = date('Y-m-d', strtotime($param['look_time'])) . ' 00:00:00';
        $mongodb_huanxin   = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        # 判断周几 将周日转换成7
        $week      = (date('w') != 0) ? date('w') : 7;
        $week_look = (date('w', strtotime($lookTime)) != 0) ? date('w', strtotime($lookTime)) : 7;
        if ($week_look >= $week) {
            $project_arr = [
                'predict_time'           => 1,
                'publish_time'           => 1,
                'contribution_name'      => 1,
                'industry_id'            => 1,
                'station_id'             => 1,
                'region_id'              => 1,
                'contribution_value'     => 1, //贡献度
                'contribution_degree'    => 1, //贡献值
                'concentration'          => 1,
                'non_industry_region_id' => 1,
            ];
            if ((int)date('H') >= 14) {
                $nowTime = date('Y-m-d 14:00:00');
            } else {
                $nowTime = date('Y-m-d') . ' 00:00:00';
            }
            $match_arr = [
                'industry_id'            => (int)$param['industry_id'],
//                'region_id'              => (int)$param['region_id'],
                'station_id'             => (int)$param['station_id'],
                'contribution_name'      => strtoupper($param['pollutant_name']),
                'non_industry_region_id' => ['$in' => $non_region_id_arr],
                'publish_time'           => $nowTime,
//                'publish_time'           => '2019-07-22 14:00:00',
                'predict_time'           => $lookTime,

            ];
        } else {
            $project_arr = [
                'predict_time'           => 1,
                'publish_time'           => 1,
                'contribution_name'      => 1,
                'industry_id'            => 1,
                'station_id'             => 1,
                'region_id'              => 1,
                'contribution_value'     => 1, //贡献度
                'contribution_degree'    => 1, //贡献值
                'concentration'          => 1,
                'non_industry_region_id' => 1,
                'difference'             => ['$eq' => ['$publish_time', '$predict_time']]
            ];
            $match_arr   = [
                'difference'             => true,
                'industry_id'            => (int)$param['industry_id'],
//                'region_id'              => (int)$param['region_id'],
                'station_id'             => (int)$param['station_id'],
                'contribution_name'      => strtoupper($param['pollutant_name']),
                'non_industry_region_id' => ['$in' => $non_region_id_arr],
                'publish_time'           => $lookTime,
            ];
        }
        $document           = [
            'aggregate'    => 'air_quality_pollutant_non_industry_area_forecast_day',
            'pipeline'     => [
                [
                    '$project' => $project_arr,
                ],
                [
                    '$match' => $match_arr,
                ],
                [
                    '$group' => [
                        '_id'               => '$non_industry_region_id',
                        'total'             => ['$sum' => '$contribution_degree'],
                        'concentration_sum' => ['$avg' => '$concentration']
                    ]
                ],
                [
                    '$sort' => [
                        '_id' => 1,
                    ]
                ]
            ],
            'allowDiskUse' => false,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $num                = count($contribution_trend[0]['result']);

        $non_region_arr = array_column($non_region, null, 'id');
        $list           = [];
        if ($num > 0) {
            for ($i = 0; $i < $num; $i++) {
                $list['date'][$i] = $non_region_arr[$contribution_trend[0]['result'][$i]['_id']]['name'];
//                $list['data'][0][$i] = $contribution_trend[0]['result'][$i]['concentration_sum'] > 0 ? $contribution_trend[0]['result'][$i]['total'] / $contribution_trend[0]['result'][$i]['concentration_sum'] : '';
                $list['data'][0][$i] = $contribution_trend[0]['result'][$i]['concentration_sum'] > 0 ? $commonService->contributionRound($contribution_trend[0]['result'][$i]['total'] / $contribution_trend[0]['result'][$i]['concentration_sum']) : '';
            }
        } else {
            for ($i = 0; $i < count($non_region_arr); $i++) {
                $list['date'][$i]    = $non_region[$i]['name'];
                $list['data'][0][$i] = '';
            }
        }
        for ($m = 0; $m < count($list['data'][0]); $m++) {
//            $list['data'][0][$m] = ($list['data'][0][$m] > 0) ? ($list['data'][0][$m] * 100) : $list['data'][0][$m];
            $list['data'][0][$m] = ($list['data'][0][$m] > 0) ? ($list['data'][0][$m]) : $list['data'][0][$m];
        }
        # 从高到低排序
        $new = [];
        for ($x = 0; $x < count($list['date']); $x++) {
            $new[$x] = ['date' => $list['date'][$x], 'data' => $list['data'][0][$x]];
        }
        $contribution_data = array_column($new, 'data');
        array_multisort($contribution_data, SORT_DESC, $new);
        $list['date']    = array_column($new, 'date');
        $list['data'][0] = array_column($new, 'data');
        return $list;
    }

    /**
     * 首要污染物比较
     * @author yy by 2019/7/4
     * @param array $param
     * @return array
     */
    public function getHistorySameData($param = [])
    {
        $commonService = new CommonService();
        $week          = date('w');
        // 查看历史日期中静稳指数一样的日期
        $yesterday = date('Y-m-d', strtotime("-1 day"));
        $today     = date('Y-m-d', time());

        $static_before      = Db::query("select stable_weather_index_value as static_index, DATE_FORMAT(publish_time, '%Y-%m-%d') as date 
                              from stable_weather_index_realtime_day_new 
                              where station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') <= ? and publish_time = predict_time", [$param['station_id'], $yesterday]);
        $static_before_date = array_column($static_before, 'date');
        if ($week != 1) {
            $date_before = $commonService->getDate($param['start_time'], $yesterday);
            // 补全过去日期中本周的数据
            foreach ($date_before as $k => $v) {
                !in_array($v, $static_before_date) ? $static_before[] = ['date' => $v, 'static_index' => '-'] : '';
            }
        }

        $static_after      = Db::query("select stable_weather_index_value as static_index, DATE_FORMAT(predict_time, '%Y-%m-%d') as date 
                                  from stable_weather_index_forecast_day 
                                  where station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') = ? and DATE_FORMAT(predict_time, '%Y-%m-%d') <= ?", [$param['station_id'], $today, $param['end_time']]);
        $static_after_date = array_column($static_after, 'date');
        $date_after        = $commonService->getDate($today, $param['end_time']);
        foreach ($date_after as $k => $v) {
            // 补全今天及之后预报中本周的数据
            !in_array($v, $static_after_date) ? $static_after[] = ['date' => $v, 'static_index' => '-'] : '';
        }

        // 本周七天的日期 和 每天对应的静稳指数
        $date_now_week           = array_flip($commonService->getDate($param['start_time'], $param['end_time']));
        $static_before_inversion = array_column($static_before, null, 'date');
        $static_after_inversion  = array_column($static_after, null, 'date');
        $static_all              = array_merge($static_before_inversion, $static_after_inversion);
        foreach ($date_now_week as $k7 => &$v7) {
            $v7 = isset($static_all[$k7]) ? $static_all[$k7]['static_index'] : '-';
        }
        // 获取本周及历史首要污染物
        $primary_pollutant = $this->getWeekPrimaryPollutant($param);
        // 获取历史数据站点七参值
        $history_station_data = Db::query("select pm10,pm25,so2,no2,co,o3,o3_8hour,DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                                           from air_quality_station_aqi_realtime_day 
                                           where region_id = ? and station_id = ?", [$param['region_id'], $param['station_id']]);
        $list                 = [];
        foreach ($date_now_week as $k6 => $v6) {
            $list['date'][]    = $k6;
            $list['data'][0][] = $v6 == '-' ? [] : $this->getWeekSameDate($k6, $v6, $static_before, $primary_pollutant, $history_station_data);
        }
        foreach ($list['data'][0] as $k12 => &$v12) {
            $new = [];
            foreach ($v12 as $k13 => $v13) {
                if ($k13 == 'o3_8hour') {
                    $name = 'O3';
                } elseif ($k13 == 'pm25') {
                    $name = 'PM2.5';
                } else {
                    $name = strtoupper($k13);
                }
                $new[] = ['name' => $name, 'value' => $v13];
            }
            $v12 = $new;
        }
        $length = [];
        foreach ($list['data'][0] as $k13 => $v13) {
            $length[] = count($v13);
        }
        $max_length = max($length);
        $new_data   = [];
        for ($i = 0; $i < $max_length; $i++) {
            for ($m = 0; $m < count($list['date']); $m++) {
                $new_data[$i][$m] = isset($list['data'][0][$m][$i]) ? $list['data'][0][$m][$i] : ['name' => '', 'value' => ''];
            }
        }
        $list['data'] = $new_data;
        // 获取本周（只限本周七天）首要污染物
        $param_z  = ['region_id' => $param['region_id'], 'station_id' => $param['station_id'], 'start_date' => $param['start_time'], 'end_date' => $param['end_time']];
        $week_avg = $this->firstContaminants($param_z);
        $a        = 1;
        foreach ($week_avg['data'] as $k10 => &$v10) {
            foreach ($v10 as $k11 => &$v11) {
                $v11 = isset($list['data'][$k10][$k11]) ? $list['data'][$k10][$k11] : ['name' => '', 'value' => ''];
            }
        }
        // 获取历史同期、预报值、实际值
        $week_other = $this->chieflyPollutant($param_z);
        $result     = [];
        foreach ($week_other['data'] as $k14 => $v14) {
            foreach ($v14 as $k15 => $v15) {
                if ($v15['type'] == 1) {
                    $result['history'][$k14][$k15] = $v15;
                } elseif ($v15['type'] == 2) {
                    $result['predict'][$k14][$k15] = $v15;
                } else {
                    $result['real'][$k14][$k15] = $v15;
                }
            }
        }
        for ($n = 0; $n < count($list['date']); $n++) {
            $list['date'][$n] = date('m/d', strtotime($list['date'][$n]));
        }
        $result['history'] = ['date' => $list['date'], 'data' => array_values($result['history'])];  //历史同期
        $result['same']    = ['date' => $list['date'], 'data' => $week_avg['data']]; // 同等气象条件历史数据平均值
        $result['predict'] = ['date' => $list['date'], 'data' => array_values($result['predict'])]; //预报值
        $result['real']    = ['date' => $list['date'], 'data' => array_values($result['real'])]; //实际值
        return $result;
    }

    /**
     * 获取历史数据中与本周每一天静稳指数相同的污染物的平均值
     * @author yy by 2019/7/4
     * @param $date 查看的日期 传周几查周几
     * @param $value 查看日期的静稳指数
     * @param $history 历史静稳指数实测数据（所有）
     * @param $primary_pollutant 历史首要污染物表实测数据（实测）
     * @param $history_station_data 历史站点七参实测数据 （实测）
     * @return array
     */
    public function getWeekSameDate($date, $value, $history, $primary_pollutant, $history_station_data)
    {
        // 本周七天的日期
        $new_static = array_column($history, null, 'date');
        $same       = [];
        // 查看历史中相同指数的日期
        $same_static_date = [];
        foreach ($new_static as $k3 => $v3) {
            if (strtotime($k3) < strtotime($date) && $v3['static_index'] == $value) {
//                $same[$date]['same_static_date'][] = $k3; //与传参周几当天静稳指数相同的日期的集合
                $same_static_date[] = $k3; //与传参周几当天静稳指数相同的日期的集合
            }
        }
        $now_pollutant = [];
        foreach ($primary_pollutant as $k4 => $v4) {
            ($v4['date'] == $date) ? $now_pollutant[] = ['name' => $v4['name'], 'date' => $v4['date']] : ''; //传参是周几，就是周几的首要污染物，可能有多个
        }
        $same_static_pollutant_name = [];
        foreach ($now_pollutant as $k6 => $v6) {
//            $same[$date]['pollutant_name'][] = $v6['name'];
            $same_static_pollutant_name[] = $v6['name'];
        }
        $arr                            = [];
        $history_station_data_inversion = array_column($history_station_data, null, 'date');
        foreach ($same_static_date as $k7 => $v7) {
            foreach ($same_static_pollutant_name as $k8 => $v8) {
                if ($v8 == 'O3_8H') {
                    $pollutant = 'o3_8hour';
                } else {
                    $pollutant = strtolower(str_replace('.', '', $v8));
                }
                (isset($history_station_data_inversion[$v7][$pollutant]) && $history_station_data_inversion[$v7][$pollutant] >= 0) ? ($arr[$pollutant][] = $history_station_data_inversion[$v7][$pollutant]) : '';
//                $arr[] = $history_station_data_inversion[$v7][$pollutant];
            }
        }
        foreach ($arr as $k9 => &$v9) {
            $v9 = count($v9) > 0 ? array_sum($v9) / count($v9) : '';
        }
//        $avg = count($arr) > 0 ? array_sum($arr) / count($arr) : '';
        return $arr;
    }

    /**
     * 获取本周及历史的首要污染物
     * @author yy by 2019/7/4
     * @param array $param
     * @return array
     */
    public function getWeekPrimaryPollutant($param = [])
    {
        $week        = date('w');
        $today       = date('Y-m-d', time());
        $data_before = Db::query("select name, value, DATE_FORMAT(publish_time, '%Y-%m-%d') as date 
                           from air_quality_station_primary_pollutant_realtime_day 
                           where region_id = ? and station_id = ?", [$param['region_id'], $param['station_id']]);
        $data_after  = Db::query("select name, value,id, DATE_FORMAT(predict_time, '%Y-%m-%d') as date 
                           from air_quality_station_primary_pollutant_forecast_day 
                           where region_id = ? and station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') = ? and DATE_FORMAT(predict_time, '%Y-%m-%d') <= ? and publish_time like '%00:00:00%'",
            [$param['region_id'], $param['station_id'], $today, $param['end_time']]);
        $data        = array_merge($data_before, $data_after);
        return $data;
    }

    /**
     * first author zz
     * 获取首要污染物 （本周）
     * @author yy by 2019/7/4
     * @param array $param
     * @return mixed
     */
    public function firstContaminants($param = [])
    {
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        $data['date'] = $lastYearWeek;
        //通过日期判断是预测值还是实际值
        if (strtotime($param['end_date']) <= strtotime(date('Y-m-d', time()))) {
            //实际值(上周或者过去时间段)
            $sql_history = "select name,value,publish_time as pt_time from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
            $list        = Db::query($sql_history, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d', time()));
            if ($days > 1) {
                //实际+预报（本周或者今天日期在所选日期范围内）
                //实际
                $sql_week = "select name,value,publish_time as pt_time from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
                $weekList = Db::query($sql_week, array($param['region_id'], $param['station_id'], $param['start_date'], date("Y-m-d", strtotime("-1 day"))));
                //预报
                $sql_forecast = "select name,value,predict_time as pt_time from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                $forecastList = Db::query($sql_forecast, array($param['region_id'], $param['station_id'], date("Y-m-d", time()), $param['end_date'], date("Y-m-d", time())));
                if (count($weekList) > 0 && count($forecastList) > 0) {
                    $list = array_merge($weekList, $forecastList);
                } else {
                    if (count($weekList) > 0) {
                        $list = $weekList;
                    } else if (count($forecastList) > 0) {
                        $list = $forecastList;
                    } else {
                        $list = [];
                    }
                }
            } else {
                //预报（未来日期范围，包括今天）
                $sql  = "select name,value,predict_time as pt_time from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                $list = Db::query($sql, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date'], date("Y-m-d", time())));
            }
        }
        if (count($list) <= 0) {
            foreach ($lastYearWeek as $k => $v) {
                $data['data'][0][] = ['name' => '', 'value' => ''];
            }
        } else {
            $newList = [];
            $newDate = [];
            for ($i = 0; $i < count($list); $i++) {
                if ($list[$i]['name'] == 'co' || $list[$i]['name'] == 'CO') {
                    $list[$i]['value'] = round($list[$i]['value'], 1);
                } else {
                    $list[$i]['value'] = round($list[$i]['value']);
                }
                $newList[date("m/d", strtotime($list[$i]['pt_time']))][] = $list[$i];
                array_push($newDate, date('m/d', strtotime($list[$i]['pt_time'])));
            }
            $newDate = array_values(array_unique($newDate));//去重，重新排列索引
            foreach ($newList as $k1 => $v1) {
                //处理O3和O3_8H
                for ($i = 0; $i < count($v1); $i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList[$k1], $i, 1);//删除数组元素，索引重组
                        }
                    }
                }
            }
            $temp = [];
            foreach ($newList as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            foreach ($lastYearWeek as $k => $v) {
                for ($j = 0; $j < max($temp); $j++) {
                    if (isset($newList[$v][$j])) {
                        if (in_array($v, $newDate)) {
                            if (strtoupper($newList[$v][$j]['name']) == 'O3_8H') {
                                $newList[$v][$j]['name'] = 'O3';
                            }
                            $data['data'][$j][] = ['name' => strtoupper($newList[$v][$j]['name']), 'value' => $newList[$v][$j]['value']];
                        } else {
                            $data['data'][$j][] = ['name' => '', 'value' => ''];
                        }
                    } else {
                        $data['data'][$j][] = ['name' => '', 'value' => ''];
                    }
                }

            }
        }
        return $data;
    }

    /**
     * author by zz
     * 获取指定日期段内每一天的日期(m/d)
     * @param  Date $startdate 开始日期
     * @param  Date $enddate 结束日期
     * @return Array
     */
    function getDateFromRange($startdate, $enddate)
    {
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400 + 1;
        // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('m/d', $stimestamp + (86400 * $i));
        }
        return $date;
    }

    /**
     * @author zhugeng 2019-05-07
     * @param $day1 开始日期
     * @param $day2 结束日期
     * @return float|int 相差天数
     */
    function diffBetweenTwoDays($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp     = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    /**
     * first author zz
     * @author yy by 2019/7/4
     * @return mixed
     */
    public function chieflyPollutant($param = [])
    {
//        $data = [];
        //本周
//        $param = $this->request->param();
        //日期判断
        if (!isset($param['start_date']) && !isset($param['end_date'])) {
            //本周
            $todayYearWeek       = self::get_week();
            $param['start_date'] = $todayYearWeek[1];
            $param['end_date']   = $todayYearWeek[7];
        } else {
            $todayYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        }
//        if (empty($param['region_id'])) {
//            return $this->error('参数错误!');
//        }

        $data['date'] = $todayYearWeek;
        $sqlHistory   = 'select publish_time as dt_time,name,value from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
        //历史同期数据（去年本周）
        $his_start     = date("Y-m-d", strtotime("-1 year", strtotime($param['start_date'])));
        $his_end       = date("Y-m-d", strtotime("-1 year", strtotime($param['end_date'])));
        $historyResult = Db::query($sqlHistory, array($param['region_id'], $param['station_id'], $his_start, $his_end));
        $num           = 0;
        $num1          = 0;
        if (count($historyResult) <= 0) {
            foreach ($todayYearWeek as $k => $v) {
                $data['data'][0][] = ['name' => '', 'value' => '', 'type' => 1];
            }
        } else {
            //历史值数据处理
//            $data['historical'] = [];
            $newList1 = [];
            foreach ($historyResult as $k => $v) {
                if ($v['name'] == 'CO') {
                    $v['value'] = round($v['value'], 1);
                } else {
                    $v['value'] = round($v['value']);
                }
                $newList1[date("m/d", strtotime($v['dt_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
            }
            foreach ($newList1 as $k1 => $v1) {
                //处理O3和O3_8H
                for ($i = 0; $i < count($v1); $i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList1[$k1], $i, 1);//删除数组元素，索引重组
                        }
                    }
                }

            }
            $temp = [];
            foreach ($newList1 as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            $num = max($temp);
            for ($j = 0; $j < max($temp); $j++) {
                for ($k = 0; $k < count($newList1); $k++) {
                    if (!isset($newList1[$todayYearWeek[$k]][$j]['name'])) {
                        $data['data'][$j][] = ['name' => '', 'value' => '', 'type' => 1];
                    } else {
                        if (strtoupper($newList1[$todayYearWeek[$k]][$j]['name']) == 'O3_8H') {
                            $newList1[$todayYearWeek[$k]][$j]['name'] = 'O3';
                        }
                        $data['data'][$j][] = ['name' => strtoupper($newList1[$todayYearWeek[$k]][$j]['name']), 'value' => $newList1[$todayYearWeek[$k]][$j]['value'], 'type' => 1];
                    }
                }
            }
        }
        if (strtotime($param['end_date']) < strtotime(date('Y-m-d', time()))) {
            //实际
            $sql_forecast_over = "select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ?  and predict_time = publish_time";
            $forecastResult    = Db::query($sql_forecast_over, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
        } else {
            //预报
            $sql_forecast_over1 = "select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ?  and publish_time = predict_time";
            $forecastResult1    = Db::query($sql_forecast_over1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', date("Y-m-d 00:00:00", strtotime("-1 day"))));
            //预报
            $sql_forecast_over2 = "select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ?  and publish_time = ?";
            $forecastResult2    = Db::query($sql_forecast_over2, array($param['region_id'], $param['station_id'], date('Y-m-d 00:00:00', time()), $param['end_date'] . ' 00:00:00', date('Y-m-d', time())));
            $forecastResult     = array_merge_recursive($forecastResult1, $forecastResult2);
        }

        if (count($forecastResult) <= 0) {
            foreach ($todayYearWeek as $k => $v) {
                $data['data'][$num + 1][] = ['name' => '', 'value' => '', 'type' => 2];
            }
        } else {
            $newList2 = [];
            foreach ($forecastResult as $k => $v) {
                if ($v['name'] == 'CO') {
                    $v['value'] = round($v['value'], 1);
                } else {
                    $v['value'] = round($v['value']);
                }
                if (date('H', strtotime($v['dt_time'])) == '12') {
                    array_splice($forecastResult, $k, 1);//删除数组元素，索引重组
                } else {
                    $newList2[date("m/d", strtotime($v['dt_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
                }

            }
            foreach ($newList2 as $k1 => $v1) {
                //处理O3和O3_8H
                for ($i = 0; $i < count($v1); $i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList2[$k1], $i, 1);//删除数组元素，索引重组
                        }
//                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3') {
//                            array_splice($newList2[$k1],$i,1);//删除数组元素，索引重组
//                        }
//                        if (strtoupper($v2['name']) == 'O3_8H' && strtoupper($v1[$i]['name']) == 'O3_8H') {
//                            array_splice($newList2[$k1],$i,1);//删除数组元素，索引重组
//                        }
                    }
                }
            }
            $temp = [];
            foreach ($newList2 as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            $num1 = $num + max($temp);
            for ($j = 0; $j < max($temp); $j++) {
                for ($k = 0; $k < count($todayYearWeek); $k++) {
                    if (!isset($newList2[$todayYearWeek[$k]][$j]['name'])) {
                        $data['data'][$num + $j + 1][] = ['name' => '', 'value' => '', 'type' => 2];
                    } else {
                        if (strtoupper($newList2[$todayYearWeek[$k]][$j]['name']) == 'O3_8H') {
                            $newList2[$todayYearWeek[$k]][$j]['name'] = 'O3';
                        }
                        $data['data'][$num + $j + 1][] = ['name' => strtoupper($newList2[$todayYearWeek[$k]][$j]['name']), 'value' => $newList2[$todayYearWeek[$k]][$j]['value'], 'type' => 2];
                    }
                }
            }
        }

        //实际值
        $sqlpractical = 'select publish_time as dt_time,name,value from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
        $list         = Db::query($sqlpractical, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
        if (count($list) <= 0) {
            foreach ($todayYearWeek as $k => $v) {
                $data['data'][$num1 + 1][] = ['name' => '', 'value' => '', 'type' => 3];
            }
        } else {
            $newList3 = [];
            foreach ($list as $k => $v) {
                if ($v['name'] == 'CO') {
                    $v['value'] = round($v['value'], 1);
                } else {
                    $v['value'] = round($v['value']);
                }
                $newList3[date("m/d", strtotime($v['dt_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
            }
            foreach ($newList3 as $k1 => $v1) {
                //处理O3和O3_8H
                for ($i = 0; $i < count($v1); $i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList3[$k1], $i, 1);//删除数组元素，索引重组
                        }
                    }
                }

            }
            $temp = [];
            foreach ($newList3 as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            for ($j = 0; $j < max($temp); $j++) {
                for ($k = 0; $k < count($todayYearWeek); $k++) {
                    if (!isset($newList3[$todayYearWeek[$k]][$j]['name'])) {
                        $data['data'][$num1 + $j + 1][] = ['name' => '', 'value' => '', 'type' => 3];
                    } else {
                        if (strtoupper($newList3[$todayYearWeek[$k]][$j]['name']) == 'O3_8H') {
                            $newList3[$todayYearWeek[$k]][$j]['name'] = 'O3';
                        }
                        $data['data'][$num1 + $j + 1][] = ['name' => strtoupper($newList3[$todayYearWeek[$k]][$j]['name']), 'value' => $newList3[$todayYearWeek[$k]][$j]['value'], 'type' => 3];
                    }
                }
            }
        }
        return $data;
//        $this->success('成功', $data);
    }

    /**
     * first author zz
     * 获取本周所有日期
     */
    function get_week($time = '', $format = 'm/d')
    {
        $time = $time != '' ? $time : time();
        //获取当前周几
        $week = date('w', $time);
        $date = [];
        for ($i = 1; $i <= 7; $i++) {
            $date[$i] = date($format, strtotime('+' . $i - $week . ' days', $time));
        }
        return $date;
    }

}